package com.sven.consumer;

import com.alibaba.fastjson2.JSON;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@Slf4j
@RestController
public class MainController {

    @Autowired
    DiscoveryClient client;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    EurekaClient client2;

    @Autowired
    LoadBalancerClient loadBalancerClient;

    @GetMapping("/client")
    public String client(){
        List<String> services = client.getServices();
        //["eureka-consumer","eureka-provider"]
        log.info("getServices()的结果：{}", JSON.toJSON(services));

        List<ServiceInstance> instances = client.getInstances("EUREKA-PROVIDER");
        log.info("getInstances(\"EUREKA-PROVIDER\")的结果：{}", JSON.toJSON(instances));

        ServiceInstance serviceInstance = instances.get(0);
        String url = serviceInstance.getUri()+"/getHi";
        log.info("请求的url：{}", url);
        String str = restTemplate.getForObject(url, String.class);
        log.info("getHi的结果：{}", str);
        return str;
    }

    @GetMapping("/client2")
    public String client2(){
        List<InstanceInfo> instances = client2.getInstancesByVipAddress("EUREKA-PROVIDER", false);

        log.info("getInstancesByVipAddress()的结果：{}", JSON.toJSON(instances));

        InstanceInfo instanceInfo = instances.get(0);
        String url = "http://" + instanceInfo.getHostName() +":"+ instanceInfo.getPort() + "/getHi";
        log.info("请求的url：{}", url);
        String str = restTemplate.getForObject(url, String.class);
        log.info("getHi的结果：{}", str);
        return str;
    }

    @GetMapping("/client3")
    public String client3(){
        // 当你使用LoadBalancerClient的时候，RestTemplate要去掉@LoadBalanced注解；不然会导致两种方式冲突，报错“No instances available for....”。
        // ribbon 完成客户端的负载均衡，过滤掉down了的节点
        ServiceInstance serviceInstance = loadBalancerClient.choose("EUREKA-PROVIDER");

        log.info("choose()的结果：{}", JSON.toJSON(serviceInstance));

        String url = serviceInstance.getUri() + "/getHi";
        // String url = "http://" + serviceInstance.getHost() +":"+ serviceInstance.getPort() + "/getHi";
        log.info("请求的url：{}", url);
        String str = restTemplate.getForObject(url, String.class);
        log.info("getHi的结果：{}", str);
        return str;
    }
}

